import {
  AfterViewInit, Component, ElementRef, EventEmitter, Input, OnChanges, OnInit, Output,
  ViewChild, SimpleChange
} from '@angular/core';
import {Hotspot} from '../../models/hotspot';

@Component({
  selector: 'app-baidu-map',
  templateUrl: './baidu-map.component.html',
  styleUrls: ['./baidu-map.component.css']
})
export class BaiduMapComponent implements OnInit, AfterViewInit, OnChanges {
  // url = 'http://api.map.baidu.com/api?v=2.0&ak=Bc4bqm4woP6gMOyoVOTAEIAp4Q48EeTb'

  constructor() { }

  @ViewChild('map')
  mapDiv: ElementRef;
  map: any;
  @Input() hotspots: Hotspot[];
  // 暂时输出布尔值绑定浮动窗状态，之后需要输出点击点信息
  @Input() ischecked: boolean;
  @Input() isfiltered: boolean;
  @Output() change: EventEmitter<boolean> = new EventEmitter<boolean>();

  ngOnInit() {
  }
  // loadJS(url) {
  //   const script = document.createElement('script');
  //   script.type = 'text/javascript';
  //   script.src = url;
  //   script.onerror = function() {
  //     document.body.removeChild(script);
  //   };
  //   document.body.appendChild(script);
  // }
  getMap() {
    if (!this.map) {
      const BMap = (<any>window)['BMap'];
      this.map = new BMap.Map(this.mapDiv.nativeElement);    // 创建Map实例
    }
    return this.map
  }
  ngAfterViewInit() {
    const BMap = (<any>window)['BMap'];
    const map = this.getMap()
    // map.centerAndZoom(new BMap.Point(120.19, 30.26), 15);  // 初始化地图,设置中心点坐标和地图级别
    // map.addControl(new BMap.MapTypeControl());   // 添加地图类型控件
    map.enableScrollWheelZoom(true);     // 开启鼠标滚轮缩放
    this.setHotspots(BMap, map)
    this.scaleToFit(BMap, map)
  }
  ngOnChanges(changes: { [propName: string]: SimpleChange }) {
    if (changes.isfiltered) {
      if (changes.isfiltered.currentValue === true) {
        this.refreshHotspot();
      }
    }
    if (changes.ischecked){
      if (changes.ischecked.currentValue === false) {
        this.refreshHotspot();
      }
    }
  }
  // 初始化标注设置
  setHotspots(BMap, map) {
    const self = this;
    let myIcon: any;
    let fontColor: string = 'black';
    if (self.isfiltered === true) {
      myIcon = new BMap.Icon('/assets/images/marker-red.png', new BMap.Size(19, 25), {
      });
      fontColor = '#bb3425'
    } else {
      myIcon = new BMap.Icon('/assets/images/marker-gray.png', new BMap.Size(19, 25), {
      });
      fontColor = 'black'
    }
    this.hotspots.forEach(function(item, index, array){
      const point = new BMap.Point(item.lng, item.lat);
      const marker = new BMap.Marker(point, {icon: myIcon});  // 创建标注
      map.addOverlay(marker);              // 将标注添加到地图中
      const label = new BMap.Label(item.title, {offset: new BMap.Size(15, -5)});
      label.setStyle({
        color : fontColor,
        fontSize : '20px',
        fontWeight: 'bold',
        height : '18px',
        lineHeight : '18px',
        fontFamily: '楷体',
        border: 'none',
        background: 'transparent'
      })
      marker.setLabel(label);
      // 为点击事件增加移动镜头效果和标注变蓝效果
      marker.addEventListener('click', function () {
        const span = map.getBounds().toSpan()
        const lngRatio = 0.36 // change these two values to get suitable offsets
        const latRatio = 0.36
        const newCenter = {
          lng: item.lng + span.lng * lngRatio,
          lat: item.lat - span.lat * latRatio,
        }
        if (self.ischecked === true) {
          self.refreshHotspot();
        }
        map.panTo(new BMap.Point(newCenter.lng, newCenter.lat))
        const checkedIcon = new BMap.Icon('/assets/images/marker-blue.png', new BMap.Size(19, 25))
        const buleMarker = new BMap.Marker(point, {icon: checkedIcon})
        map.removeOverlay(marker);
        map.addOverlay(buleMarker);
        label.setStyle({
          color: '#349ba2'
        });
        buleMarker.setLabel(label);
        self.ischecked = true;
        self.change.emit(self.ischecked);
        console.dir(self.ischecked)
      })
    })
  }
  //
  refreshHotspot() {
    if (!this.map) {
      const BMap = (<any>window)['BMap'];
      this.map = new BMap.Map(this.mapDiv.nativeElement);    // 创建Map实例
    } else {
      const BMap = (<any>window)['BMap'];
      // 刷新前先清除
      this.map.clearOverlays();
      this.setHotspots(BMap, this.map)
    }
  }
  //
  scaleToFit(BMap, map) {
    const pointList = new Array<any>();
    this.hotspots.forEach(function(item, index, array){
      pointList.push(new BMap.Point(item.lng, item.lat))
    })
    const viewpoint = map.getViewport(pointList, {margins: [30, 20, 0, 20]})
    map.centerAndZoom(viewpoint.center, viewpoint.zoom)
  }
}
